import Vue from 'vue'
import VueRouter, {Route, RouteConfig } from 'vue-router'

//使用Vue.use()函数, 将VueRouter注册为Vue的插件
Vue.use(VueRouter);

const routes: RouteConfig[]  = [
    {
        path: '/',
        redirect: '/home'
    },{
        path: '/home',
        component: () => import('../views/Home.vue')
    },{
        // 动态路由参数
        path: '/movie/:mid',
        component: () => import('../views/Movie.vue'),
        //当前路由规则中的路径参数在组件内可以通过props进行访问, 不再需要使用$route.params.mid进行访问
        props: true
    },{
        path: '/about',
        component: () => import('../views/About.vue'),
        children: [
            //子路由规则中, path设置空字符串,则为 '默认子路由'
            {path: '', component: () => import('../views/comp/Tab1.vue') },
            {path: 'tab2', component: () => import('../views/comp/Tab2.vue') },
        ]
    },
    // 配置meta,中的top用于记录滚动条滚动的y轴位置; 
    // 对应的组件包裹在<keep-alive>标签中缓存, 并且设置include属性,只对
    { path: '/user', component: () => import('../views/comp/User.vue'), meta: {top: 0, isRecord: true}}
]

const router = new VueRouter({
    routes,
    //滚动行为
    scrollBehavior(to: any, from, savedPosition) {
        if(savedPosition) {
            return savedPosition
        }else {
            return { x: 0, y: to.meta.top || 0} 
        }
    }
});

//路由白名单,不需要权限即可访问的路由
const whiteRoutes = [
    'login',
    'unlogin',
    'register',
    ''
];

/*
配合业务使用
router.beforeEach((to, from, next) => {
    // 1.即将跳转的路由不在白名单中, 需要权限token
    if(!whiteRoutes.includes(to.path)) {
        const token = localStorage.getItem('token');
        // 2. 无token, 强制跳转登录页
        if(!token) {
            next('/login')
        }else {
            // 3.有则放行
            next()
        }        
    }else {
        next()
    }
})

 */
export default router;